<?php

namespace app\admin\controller;
use think\Controller;
use think\Verify;
use think\captcha\Captcha;
use think\Db;
class Login extends Controller
{
    /***
     * 显示登录页面
     */
    public function index()
    {
        return $this->fetch('/login');
    }

    /**
     * 登录操作
     */
    public function dologin()
    {

        $username = input("param.uname");
        $password = input("param.password");
        $code = input("param.code");
        //dump($code);dump($_POST);exit;

        if(!captcha_check($code)){
            //dump($code);exit;
            return json(['code' => -3, 'url' => '', 'msg' => '验证码不正确,请重试']);
        };
        $hasUser = Db::name('admin')->where('username', $username)->find();
        if(empty($hasUser)){
            return json(['code' => -1, 'url' => '', 'msg' => '账号不存在']);
        }
        if(md5($password) != $hasUser['password']){
            return json(['code' => -2, 'url' => '', 'msg' => '账号或密码错误']);
        }
        if(1 != $hasUser['status']){
            return json(['code' => -6, 'url' => '', 'msg' => '该账号被禁用']);
        }
        session('uid', $hasUser['id']);         //用户ID
        session('username', $hasUser['username']);  //用户名
        //更新管理员状态
        $param = [
            'loginnum' => $hasUser['loginnum'] + 1,
            'last_login_ip' => request()->ip(),
            'last_login_time' => time(),
        ];
        $this->loginLog($hasUser);
        Db::name('admin')->where('id', $hasUser['id'])->update($param);
        return json(['code' => 1, 'url' => url('admin/index/index'), 'msg' => '登录成功！']);
    }
    /**
     * 验证码
     */
    public function checkVerify()
    {
        $verify = new Captcha();
        $verify->imageH = 32;
        $verify->imageW = 125;
        $verify->codeSet = '0123456789';
        $verify->length = 4;
        $verify->useNoise = false;
        $verify->fontSize = 14;
        return $verify->entry();
    }
    private function loginLog($user)
    {
       $ip = request()->ip();
      	$host = "https://api01.aliyun.venuscn.com";
        $path = "/ip";
        $method = "GET";
        $appcode = "df34890057ad4d10bef6c259c51ae8c7";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "ip=" . $ip;
        $bodys = "";
        $url = $host . $path . "?" . $querys;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
      	$res=curl_exec($curl);
 		$jsonAddress = json_decode($res,true);
      	if($jsonAddress['ret'] == '200' && $jsonAddress['msg'] == 'success'){
          	$loginLogModel = new \app\common\model\LoginLog();
        	$logData = [
                'uid' => $user['id'],
                'ip' => $ip,
                'admin_name' => session('username'),
                'area' => $jsonAddress['data']['area'],//地区
             	'country' => $jsonAddress['data']['country'],//国家
                'city' => $jsonAddress['data']['city'],//城市
                'isp' => $jsonAddress['data']['isp'],//运营商
                'create_time' => time(),
                'update_time' => time()
            ];
          //dump($logData);exit;
          $loginLogModel->save($logData);
        }else{
        	return false;
        }
    }
    /**
     * 退出登录
     */
    public function loginOut()
    {
        session(null);
        $this->redirect('login/index');
    }
}